<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">{{ title }}</h3>
      <el-form-item prop="username">
        <el-input
          v-model="loginForm.username"
          type="text"
          size="large"
          auto-complete="off"
          placeholder="账号"
        >
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          v-model="loginForm.password"
          type="password"
          size="large"
          auto-complete="off"
          placeholder="密码"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaEnabled">
        <el-input
          v-model="loginForm.code"
          size="large"
          auto-complete="off"
          placeholder="验证码"
          style="width: 63%"
          @keyup.enter="handleLogin"
        >
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <img :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button
          :loading="loading"
          size="large"
          type="primary"
          style="width:100%;"
          @click.prevent="handleLogin"
        >
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
      
      <!-- 第三方登录区域 -->
      <div class="third-party-login">
        <div class="divider">其他登录方式</div>
        <div class="login-icons">
          <div class="login-icon" @click="handleWechatLogin">
            <svg-icon icon-class="wechat" style="font-size: 24px; color: #07c160;" />
            <span style="font-size: 12px; color: #999; margin-top: 4px;">微信登录</span>
          </div>
          <div class="login-icon" @click="handleGithubLogin">
            <svg-icon icon-class="github" style="font-size: 24px; color: #333;" />
            <span style="font-size: 12px; color: #999; margin-top: 4px;">GitHub登录</span>
          </div>
          
        </div>
      </div>
    </el-form>
    
    
    
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
  <Wx ref="wxDialog" @handleSuccess="WechatSuccess"/>
</template>

<script setup>

import { getCodeImg } from "@/api/login"
import { wxLogin } from '@/api/wxLogin'
import Cookies from "js-cookie"
import { encrypt, decrypt } from "@/utils/jsencrypt"
import useUserStore from '@/store/modules/user'
import Wx from '@/views/components/Wx.vue'


const title = import.meta.env.VITE_APP_TITLE
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
const { proxy } = getCurrentInstance()

// 创建 ref 引用
const wxDialog = ref(null)

const loginForm = ref({
  username: "admin",
  password: "admin123",
  rememberMe: false,
  code: "",
  uuid: ""
})

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
}

const codeUrl = ref("")
const loading = ref(false)
// 验证码开关
const captchaEnabled = ref(true)
// 注册开关
const register = ref(false)
const redirect = ref(undefined)

watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect
}, { immediate: true })

function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("username", loginForm.value.username, { expires: 30 })
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 })
        Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 })
      } else {
        // 否则移除
        Cookies.remove("username")
        Cookies.remove("password")
        Cookies.remove("rememberMe")
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        const query = route.query
        console.log(query,'手动登录')
        const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
          if (cur !== "redirect") {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
        console.log(otherQueryParams,'手动登录12')
        router.push({ path: redirect.value || "/", query: otherQueryParams })
      }).catch(() => {
        loading.value = false
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode()
        }
      })
    }
  })
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img
      loginForm.value.uuid = res.uuid
    }
  })
}

function getCookie() {
  const username = Cookies.get("username")
  const password = Cookies.get("password")
  const rememberMe = Cookies.get("rememberMe")
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  }
}
function handleWechatLogin() {
  // 显示加载状态
  const loadingInstance = proxy.$loading({
    text: '正在获取微信二维码...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  // 调用后端接口获取微信二维码URL
  wxLogin()
    .then(response => {
      loadingInstance.close()
      
      if (response.code === 200 && response.data) {
        const qrCodeUrl = response.data?.qrcode 
        const token = response.data?.token
        
        if (qrCodeUrl) {
          // 使用 ref 调用组件的 open 方法展示二维码
          console.log('wxDialog.value',wxDialog.value)
          if (wxDialog.value) {
            wxDialog.value.open(qrCodeUrl,token)
          } else {
            console.error('图片预览组件引用不存在')
            proxy.$modal.msgError('组件加载失败，请刷新页面重试')
          }
        } else {
          proxy.$modal.msgError('获取二维码失败：URL不存在')
        }
      } else {
        proxy.$modal.msgError(response.msg || '获取微信二维码失败')
      }
    })
    .catch(error => {
      loadingInstance.close()
      console.error('获取微信二维码失败:', error)
      proxy.$modal.msgError('获取微信二维码失败，请检查网络连接')
    })
}

// 示例：其他使用 ref 调用组件方法的情况
function showExampleImage() {
  // 模拟调用API获取图片URL
  const mockApiCall = () => {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          code: 200,
          data: {
            imageUrl: 'https://picsum.photos/800/600?random=' + Date.now()
          }
        })
      }, 500)
    })
  }
  
  // 显示加载状态
  const loading = proxy.$loading({
    text: '正在获取图片...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  mockApiCall()
    .then(response => {
      loading.close()
      
      if (response.code === 200 && response.data.imageUrl) {
        // 检查 ref 是否存在再调用方法
        if (wxDialog.value) {
          wxDialog.value.open(response.data.imageUrl)
        } else {
          proxy.$modal.msgError('组件引用不存在或方法不可用')
        }
      } else {
        proxy.$modal.msgError('获取图片失败')
      }
    })
    .catch(error => {
      loading.close()
      console.error('获取图片失败:', error)
      proxy.$modal.msgError('获取图片失败，请重试')
    })
}

function handleGithubLogin() {
  // GitHub OAuth登录逻辑
  // 这里应该跳转到GitHub OAuth授权页面
  // const clientId = 'YOUR_GITHUB_CLIENT_ID' // 需要配置您的GitHub应用客户端ID
  // const redirectUri = encodeURIComponent(window.location.origin + '/auth/github/callback')
  // const githubAuthUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&scope=user:email`
  
  // // 打开GitHub授权页面
  // window.location.href = githubAuthUrl
  proxy.$modal.msgSuccess("github登陆即可")
}

function handleGiteeLogin() {
  // Gitee OAuth登录逻辑  
  // 这里应该跳转到Gitee OAuth授权页面
  const clientId = 'YOUR_GITEE_CLIENT_ID' // 需要配置您的Gitee应用客户端ID
  const redirectUri = encodeURIComponent(window.location.origin + '/auth/gitee/callback')
  const giteeAuthUrl = `https://gitee.com/oauth/authorize?client_id=${clientId}&redirect_uri=${redirectUri}&response_type=code&scope=user_info`
  
  // 打开Gitee授权页面
  window.location.href = giteeAuthUrl
}
const WechatSuccess = () => { 
  loading.value = true
}
onUnmounted(() => {
  loading.value = false
})
getCode()
getCookie()
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  z-index: 1;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}

.third-party-login {
  margin-top: 20px;
  text-align: center;
  padding: 0 10px;
}

.login-icons {
  display: flex;
  justify-content: center;
  gap: 20px;
  flex-wrap: wrap;
}

.divider {
  position: relative;
  margin: 20px 0;
  color: #999;
  font-size: 14px;
}

.divider::before,
.divider::after {
  content: '';
  position: absolute;
  top: 50%;
  width: 30%;
  height: 1px;
  background-color: #ddd;
}

.divider::before {
  left: 0;
}

.divider::after {
  right: 0;
}

.login-icon {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  padding: 10px;
  border-radius: 8px;
  transition: background-color 0.3s;
  min-width: 60px;
}

.login-icon:hover {
  background-color: #f5f5f5;
}
</style>
